//
//  LTGroupManager.m
//  LTChat
//
//  Created by 俊松何 on 2017/7/26.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTGroupManager.h"
#import "LTDBHelper.h"
#import "LTGroupConfig.h"
#import "LTClient.h"
#import "LTHTTPTool.h"
#import "LTChatManager.h"
#import <MJExtension/MJExtension.h>
@implementation LTGroupManager
/**
 创建群
 
 @param name             群名字
 @param description      群描述
 @param Invitees         群成员数组
 @param message          创建消息
 @param completionBlock  完成的block
 */
-(void)createGroupWithName:(NSString *)name
               description:(NSString *)description
                  invitees:(NSArray<LTUser *> *)Invitees
                   message:(NSString *)message
                completion:(void(^)(LTGroup *aGroup, LTError *aError))completionBlock
{
     NSMutableString *groupName = [NSMutableString stringWithFormat:@"%@", [LTClient sharedClient].currentUser.name];
    NSMutableArray *idsArray = [NSMutableArray arrayWithCapacity:10];
    [idsArray addObject:[LTClient sharedClient].currentUser.userId];
    
    for (LTUser *selectuser in Invitees) {
        
        groupName = [NSMutableString stringWithFormat:@"%@、%@",groupName,selectuser.name];
        [idsArray addObject:selectuser.userId];
        
    }
    NSDictionary *param = @{@"name":groupName,@"ids":[idsArray mj_JSONString]};
    [[LTHTTPTool shareTool] postPath:@"/user/group/create" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        LTGroup *group = [LTGroup mj_objectWithKeyValues:datamodel.data[@"group"]];
        group.users = [LTUser mj_objectArrayWithKeyValuesArray:datamodel.data[@"users"]];
        [[LTDBHelper sharedbhelper] AddGroup:group];
        //发送通知消息
        [self _sendGroupOperationMessage:group opeationName:[LTClient sharedClient].currentUser.name operationresult:group.name messageType:LTMessageTypeCreateGroup];
        
        completionBlock(group,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,[LTError netWorkError]);
    }];
}

/**
 添加群成员
 
 @param aUsers    要添加的群成员的数组
 @param aGroupId  群id
 @param aMessage  加入消息
 @param completionBlock 完成的block回调
 */
- (void)addMembers:(NSArray<LTUser *> *)aUsers
           toGroup:(NSString *)aGroupId
           message:(NSString *)aMessage
        completion:(void(^)(LTGroup *aGroup, LTError *aError))completionBlock
{
    
    NSMutableArray *idsArray = [NSMutableArray arrayWithCapacity:10];
    for (LTUser *selectuser in aUsers) {
        [idsArray addObject:selectuser.userId];
    }
    NSDictionary *param = @{@"groupId":aGroupId,@"ids":[idsArray mj_JSONString]};
    [[LTHTTPTool shareTool] postPath:@"/user/group/add_users" parameters:param success:^(LTBaseDataModel *datamodel) {
        LTGroup *group = [LTGroup mj_objectWithKeyValues:datamodel.data[@"group"]];
        group.users = [LTUser mj_objectArrayWithKeyValuesArray:datamodel.data[@"users"]];
        [[LTDBHelper sharedbhelper] AddGroup:group];
        
          __block  NSMutableString *usernamestring = [NSMutableString string];
        [aUsers enumerateObjectsUsingBlock:^(LTUser * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if(![obj isKindOfClass:[LTUser class]])
            {
                *stop = YES;
            }
            if( idx == 0)
            {
                usernamestring = [NSMutableString stringWithFormat:@"%@",obj.name];
            }else
            {
                usernamestring = [NSMutableString stringWithFormat:@"%@,%@",usernamestring,obj.name];
            }
        }];
        
        [self _sendGroupOperationMessage:group opeationName:[LTClient sharedClient].currentUser.name operationresult:usernamestring messageType:LTMessageTypeaddGroupMember];
        
        completionBlock(group,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
         completionBlock(nil,[LTError netWorkError]);
    }];
    
}

/**
 移除群成员
 
 @param group        群组
 @param removeUsers  要移除的群成员的数组
 @param aMessage  移除消息
 @param completionBlock 完成的block回调
 */
- (void)removeMembersWithGroup:(LTGroup *)group
                   removeUsers:(NSArray<LTUser *> *)removeUsers
              message:(NSString *)aMessage
           completion:(void(^)(LTGroup *aGroup, LTError *aError))completionBlock
{
    
    NSMutableArray *idsArray = [NSMutableArray arrayWithCapacity:10];
    for (LTUser *selectuser in removeUsers) {
        [idsArray addObject:selectuser.userId];
    }
    NSDictionary *param = @{@"groupId":group.id,@"ids":[idsArray mj_JSONString]};
    [[LTHTTPTool shareTool] postPath:@"/user/group/remove" parameters:param success:^(LTBaseDataModel *datamodel) {
      
        //通知其他人被踢出了群聊
        [self _sendKickedOutgroupMessageWithUsers:removeUsers groupId:group.id];
        
        [self getGroupDetailFromServerWithGroupId:group.id completion:^(LTGroup *aGroup, LTError *aError) {
           
             completionBlock(aGroup,nil);
            
        }];
        
       
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,[LTError netWorkError]);
    }];
    
}


/**
 解散群
 
 @param groupId 群id
 @param completionBlock 完成的回调
 */
- (void)destroyGroup:(NSString *)groupId
    finishCompletion:(void(^)(LTError *aError))completionBlock
{

    
    


}

/**
 通过群id得到群组详情
 
 @param groupId 群id
 @return  群组对象
 */
- (LTGroup *)getGroupWithGroupId:(NSString *)groupId
{
    return [[LTDBHelper sharedbhelper] getGroupWithGroupId:groupId];
}
/**
 通过群id删除本地群聊
 
 @param groupId 群id
 @return  群组对象
 */
- (BOOL)deleteGroupWithGroupId:(NSString *)groupId
{
    return [[LTDBHelper sharedbhelper] deleteGroup:groupId];

}


/**
 群成员退出群
 
 @param groupId 群id
 @param completionBlock 完成block
 */
- (void)leaveGroup:(NSString *)groupId
        completion:(void(^)(LTError *aError))completionBlock
{
    NSDictionary *param = @{@"groupId":groupId};
    [[LTHTTPTool shareTool] postPath:@"/user/group/quite" parameters:param success:^(LTBaseDataModel *datamodel) {
        //发送退群透传
        [self _sendGroupOperationCmdMessage:groupId withType:LTMessageCmdTypeQuitGroup];
        completionBlock(nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock([LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
         completionBlock([LTError netWorkError]);
        
    }];
    
}

/**
 通过群id得到群组详情
 
 @param groupId 群id
 @param completionBlock 完成的block
 */
-(void)getGroupDetailFromServerWithGroupId:(NSString *)groupId
                                completion:(void(^)(LTGroup *aGroup, LTError *aError))completionBlock
{
    NSDictionary *param = @{@"groupId":groupId};
    [[LTHTTPTool shareTool] getPath:@"/user/group/info" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        LTGroup *group = [LTGroup mj_objectWithKeyValues:datamodel.data[@"group"]];
        group.users = [LTUser mj_objectArrayWithKeyValuesArray:datamodel.data[@"users"]];
        
        [[LTDBHelper sharedbhelper] AddGroup:group];
        completionBlock(group,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,[LTError netWorkError]);
        
    }];

}

-(void)changeGroupNameWithGroup:(LTGroup *)group
                            name:(NSString *)name
                     completion:(void(^)(LTGroup *aGroup,LTMessage *uiMessage, LTError *aError))completionBlock
{
    NSDictionary *param = @{@"id":group.id,@"name":name};
    [[LTHTTPTool shareTool] postPath:@"/user/group/update" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        group.name = name;
        [[LTDBHelper sharedbhelper] AddGroup:group];
        
      LTMessage *uimessage =   [self _sendGroupOperationMessage:group opeationName:[LTClient sharedClient].currentUser.name operationresult:group.name messageType:LTMessageTypechangeGroupName];
        
        completionBlock(group,uimessage,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,nil,[LTError netWorkError]);
        
    }];

}
-(void)changeGroupNoticeWithGroup:(LTGroup *)group
                           notice:(NSString *)notice
                       completion:(void(^)(LTGroup *aGroup,LTMessage *uiMessage, LTError *aError))completionBlock
{
    NSDictionary *param = @{@"id":group.id,@"post":notice};
    [[LTHTTPTool shareTool] postPath:@"/user/group/update" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        group.post = notice;
        [[LTDBHelper sharedbhelper] AddGroup:group];
        
      LTMessage *uimessage =  [self _sendGroupOperationMessage:group opeationName:[LTClient sharedClient].currentUser.name operationresult:group.post messageType:LTMessageTypechangeGroupnotice];
        
        completionBlock(group,uimessage,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,nil, [LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil, nil,[LTError netWorkError]);
        
    }];
}
//保存群聊到通讯录
-(void)saveContactGroupWithGroup:(LTGroup *)group
                      completion:(void(^)(LTGroup *group, LTError *aError))completionBlock
{
    NSDictionary *param = @{@"groupId":group.id};
    
    [[LTHTTPTool shareTool] postPath:@"/user/group/add_to_contacts" parameters:param success:^(LTBaseDataModel *datamodel) {
        
         completionBlock(nil,nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
         completionBlock(nil,[LTError netWorkError]);
    }];
}

//从通讯录移除群聊
-(void)removeContactGroupWithGroup:(LTGroup *)group
                        completion:(void(^)(LTError *aError))completionBlock
{
    NSDictionary *param = @{@"groupId":group.id};
    
    [[LTHTTPTool shareTool] postPath:@"/user/group/remove_from_contacts" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        [[LTDBHelper sharedbhelper] deleteGroup:group.id];
        completionBlock(nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock([LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock([LTError netWorkError]);
    }];


}

/**
 退出群聊
 
 @param group 群组
 @param completionBlock 完成的block
 */
-(void)quitGroupWithGroup:(LTGroup *)group
               completion:(void(^)(LTError *aError))completionBlock
{
    NSDictionary *param = @{@"groupId":group.id};
    [[LTHTTPTool shareTool] postPath:@"/user/group/quite" parameters:param success:^(LTBaseDataModel *datamodel) {
        [[LTDBHelper sharedbhelper] deleteGroup:group.id];
        [[LTDBHelper sharedbhelper] DeleteConversationWithConversationID:group.id];
        completionBlock(nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock([LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock([LTError netWorkError]);
        
    }];
}

/**
 获取所有的群租列表
 
 @param completionBlock 回调
 */
-(void)getAllGroupFromServerWithCompletion:(void(^)(NSArray<LTGroup *> *groups, LTError *aError))completionBlock
{
    NSDictionary *param = @{@"page":@"0"};
    [[LTHTTPTool shareTool] getPath:@"/user/group/get_my_all_groups" parameters:param success:^(LTBaseDataModel *datamodel) {
        
      NSMutableArray *groupArray = [LTGroup mj_objectArrayWithKeyValuesArray:datamodel.data[@"list"]];
      [[LTDBHelper sharedbhelper] updateMyGroups:groupArray];
      
       completionBlock(groupArray,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
         completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,[LTError netWorkError]);
    }];
}


/**
 获取推荐群租
 
 @param completionBlock 完成的block
 */
-(void)getRecommendGroupFromServerWithCompletion:(void(^)(NSArray<LTRecommendGroups *> *recomendgroups, LTError *aError))completionBlock
{
    [[LTHTTPTool shareTool] getPath:@"/user/group/get_recommend_groups_ios" parameters:nil success:^(LTBaseDataModel *datamodel) {
        
        NSMutableArray *groupArray = [LTRecommendGroups mj_objectArrayWithKeyValuesArray:datamodel.data];
    
        completionBlock(groupArray,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionBlock(nil,[LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionBlock(nil,[LTError netWorkError]);
    }];
    
    
}

//获取本地我的群组列表
-(NSArray<LTGroup *> *)getGroupListFromLocal
{
      return  [[LTDBHelper sharedbhelper] getMyGroupList];

}


#pragma mark   ----群操作发消息的私有方法
//发送群操作消息   //(ui显示消息)
-(LTMessage *)_sendGroupOperationMessage:(LTGroup *)groupmodel
                    opeationName:(NSString *)operationNmae
                 operationresult:(NSString *)operationresult
                     messageType:(LTMessageType)messagetype
{
    
    LTUser *user = [[LTUser alloc] init];
    user.name = groupmodel.name;
    user.userId = groupmodel.id;
    user.type = LTUserTypeGroup;
    user.avatar = groupmodel.avatar;
    
    LTMessage *message = [self _sendGroupOperationMessage:operationNmae operationresult:operationresult toUserId:user.userId toUser:user messageType:messagetype  messageExt:nil];
    
    [[LTClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
    } completion:^(LTMessage *message, LTError *error) {
        
    }];
    
    return message;
}
//发送退群透传消息 //(后台操作消息)
-(void)_sendGroupOperationCmdMessage:(NSString *)groupId withType:(LTMessageCmdType)type
{
    
    LTUser *user = [[LTUser alloc] init];
    user.name = @"   ";
    user.userId =groupId;
    user.type = LTUserTypeGroup;
    
    LTMessageCmdBody *body = [[LTMessageCmdBody alloc] initWithType:type data:groupId];
    LTUser *fromUser = [LTClient sharedClient].currentUser;
    LTMessage *message = [[LTMessage alloc] initWithConversationID:groupId
                                                        fromUserId:fromUser.userId
                                                          toUserId:user.userId
                                                          fromUser:fromUser
                                                            toUser:user
                                                              type:LTMessageTypeCMD
                                                              body:body
                                                          chatType:LTChatTypeGroupChat
                                                               ext:nil];
    
    [[LTClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
    } completion:^(LTMessage *message, LTError *error) {
        
    }];

}

//群主通知其他人被踢出了群聊
-(void)_sendKickedOutgroupMessageWithUsers:(NSArray<LTUser *> *)users groupId:(NSString *)groupId
{
    
    for (LTUser *kickedUser in users) {
        LTMessageCmdBody *body = [[LTMessageCmdBody alloc] initWithType:LTMessageCmdTypeKickedOutGroup data:groupId];
        LTUser *fromUser = [LTClient sharedClient].currentUser;
        
        LTMessage *message = [[LTMessage alloc] initWithConversationID:kickedUser.userId
                                                            fromUserId:fromUser.userId
                                                              toUserId:kickedUser.userId
                                                              fromUser:fromUser
                                                                toUser:kickedUser
                                                                  type:LTMessageTypeCMD
                                                                  body:body
                                                              chatType:LTChatTypeChat
                                                                   ext:nil];
        [[LTClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
            
        } completion:^(LTMessage *message, LTError *error) {
            
        }];

        
    }
}

-(void)getGroupConfigWithGroupId:(NSString *)groupId
                      completion:(void(^)(LTGroupConfig *userConfig,LTError *ltrror))CompletionBlock
{
    
    
    LTGroupConfig *config = [[LTDBHelper sharedbhelper] getGroupConfigWithGroupId:groupId];
    
    if(config != nil)
    {
        CompletionBlock(config,nil);
    }else{
        NSDictionary *param = @{@"groupId":groupId};
        [[LTHTTPTool shareTool] postPath:@"/user_config/get_group_config" parameters:param success:^(LTBaseDataModel *datamodel) {
            LTGroupConfig *groupconifg = [LTGroupConfig mj_objectWithKeyValues:datamodel.data];
            [[LTDBHelper sharedbhelper] AddOrUpdateGroupConfig:groupconifg];
            
            CompletionBlock(groupconifg,nil);
            
        } parmerror:^(LTBaseDataModel *datamodel) {
            LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
            CompletionBlock(nil,lterror);
        } failer:^(NSError *error) {
            LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
            CompletionBlock(nil,lterror);
        }];
    }
}


-(void)updateGroupConfigWithGroupConfig:(LTGroupConfig *)groupconfig
                             completion:(void(^)(LTGroupConfig *userConfig,LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{ @"id":groupconfig.id,
                             @"groupId":groupconfig.groupId,
                             @"chatBackground":groupconfig.chatBackground,
                             @"myNameInGroup":groupconfig.myNameInGroup,
                             @"notify":@(groupconfig.notify),
                             @"push":@(groupconfig.push),
                             @"saveContacts":@(groupconfig.saveContacts),
                             @"showUserNickname":@(groupconfig.showUserNickname),
                             @"top":@(groupconfig.top),
                           };
    
    
    [[LTHTTPTool shareTool] postPath:@"/user_config/update_group_config" parameters:param success:^(LTBaseDataModel *datamodel) {
        
        LTGroupConfig *conifg = [LTGroupConfig mj_objectWithKeyValues:datamodel.data];
        [[LTDBHelper sharedbhelper] AddOrUpdateGroupConfig:groupconfig];
        CompletionBlock(conifg,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
        CompletionBlock(nil,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        CompletionBlock(nil,lterror);
    }];
    
    
    
}
//发送群操作消息
-(LTMessage *)_sendGroupOperationMessage:(NSString *)operationname
                         operationresult:(NSString *)operationresult
                                toUserId:(NSString *)groupId
                                  toUser:(LTUser *)toUser
                             messageType:(LTMessageType)messageType
                              messageExt:(NSDictionary *)messageExt
{
    LTMessageGroupOperationBody *body = [[LTMessageGroupOperationBody alloc] initWithoperationname:operationname operationresult:operationresult];
    LTUser *fromUser = [LTClient sharedClient].currentUser;
    LTMessage *message = [[LTMessage alloc] initWithConversationID:groupId
                                                        fromUserId:fromUser.userId
                                                          toUserId:groupId
                                                          fromUser:fromUser
                                                            toUser:toUser
                                                              type:messageType
                                                              body:body
                                                          chatType:LTChatTypeGroupChat
                                                               ext:nil];
    
    return message;
}




@end
